<template>
  <div class="app">
    <div class="header" style="margin-left: 10px">
      <el-form :inline="true" :model="form" class="demo-form-inline" style="padding-top: 20px">
        <el-form-item label="类型名称">
          <el-input v-model="form.name" placeholder="类型名称"></el-input>
        </el-form-item>
        <el-form-item label="收支类型">
          <el-select v-model="form.type" placeholder="状态">
            <el-option label="支出" value="0"></el-option>
            <el-option label="收入" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="状态">
            <el-option label="停用" value="0"></el-option>
            <el-option label="启用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否定制">
          <el-select v-model="form.exclusive" placeholder="是否定制">
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="select" icon="el-icon-search" type="primary">查询</el-button>
          <el-button @click="reset" icon="el-icon-refresh-right">重置</el-button>
          <el-button @click="addNew" icon="el-icon-edit-outline" type="primary">录入</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="dia">
      <el-dialog
          title="录入记账类型"
          :visible.sync="dialogVisible"
          width="35%"
          class="dialog"
          :before-close="handleClose">
        <el-form :model="newForm" :rules="rules" status-icon ref="newForm" label-width="100px" class="newForm">
          <el-form-item label="类型图标">

            <el-upload
                class="avatar-uploader"
                action="api/bill/uploadImg"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="token"
            >
              <el-image v-if="url" :src="url" class="avatar"></el-image>
              <i class="el-icon-plus avatar-uploader-icon upIcon" v-else
                 style="height: 120px;width: 120px;border-radius: 50%;border: 1px dashed #dcdbdb;margin-left: 25%"></i>
            </el-upload>
            <span style="margin-left: 25%;cursor: pointer;color: deepskyblue" @click="openMaterial">素材库</span>
          </el-form-item>
          <el-form-item label="收支类型">
            <el-radio-group v-model="newForm.type" size="medium">
              <el-radio-button label="0" checked>支出</el-radio-button>
              <el-radio-button label="1">收入</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="类型名称" prop="name">
            <el-input v-model="newForm.name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">提 交</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="table">
      <el-table
          :data="type"
          :fit="true"
          :lazy="false"
          :key="randomKey"
          class="table"
          size="mini"
          style="width: 95%;text-align: center">
        <el-table-column
            fixed
            prop="groupId"
            label="图标"
            align="center"
            head-align="center"
            width="60">
          <template v-slot="scope">
            <el-avatar size="50" :src="scope.row.groupId" @error="errorHandler"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column
            fixed
            prop="name"
            label="名称"
            sortable
            align="center"
            head-align="center"
            width="100">
          <template v-slot="scope">
            <el-input v-if="scope.row.editFlag" v-model="scope.row.name"></el-input>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="type"
            label="分类"
            sortable
            align="center"
            head-align="center"
            width="150">
          <template v-slot="scope">
            <el-radio-group v-model="scope.row.type" size="mini" v-if="scope.row.editFlag">
              <el-radio-button label="0">支出</el-radio-button>
              <el-radio-button label="1">收入</el-radio-button>
            </el-radio-group>
            <span v-else>{{ scope.row.type === 1 ? '收入' : '支出' }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            align="center"
            sortable
            head-align="center"
            width="140">
          <template v-slot="scope">
            <el-switch
                v-if="scope.row.editFlag"
                style="display: block"
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="停用">
            </el-switch>
            <span v-else>{{ scope.row.status ? '启用' : '停用' }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="exclusive"
            label="是否定制"
            align="center"
            sortable
            head-align="center"
            width="120">
          <template v-slot="scope">
            <el-switch
                v-if="scope.row.editFlag"
                style="display: block"
                v-model="scope.row.exclusive"
                active-color="#409eff"
                inactive-color="#cacaca"
                active-text="是"
                inactive-text="否">
            </el-switch>
            <span v-else>{{ scope.row.exclusive ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建日期"
            align="center"
            head-align="center"
            sortable
            width="130">
          <template v-slot="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="createBy"
            align="center"
            head-align="center"
            label="创建者"
            width="120">
          <template v-slot="scope">
            <span>{{ scope.row.createBy }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="updateTime"
            label="修改日期"
            align="center"
            sortable
            head-align="center"
            width="200">
          <template v-slot="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="updateBy"
            align="center"
            head-align="center"
            label="修改者"
            width="120">
          <template v-slot="scope">
            <span>{{ scope.row.updateBy }}</span>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            align="center"
            head-align="center"
            label="操作"
            width="150">
          <template slot-scope="scope">
            <el-button @click="editRow(scope.row)" :type="scope.row.editFlag ? 'primary' : '' "
                       size="small">{{
                scope.row.editFlag ? '完成' : '编辑'
              }}
            </el-button>
            <el-button @click="deleteRow(scope.row)" :type="scope.row.editFlag ? '' : 'danger' "
                       size="small">{{ scope.row.editFlag ? '取消' : '删除' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="material">
      <el-dialog
          title="素材库"
          :visible.sync="materialDia"
          width="50%"
          :before-close="materialClose">
        <div v-for="img in material" :key="img.url" style="display: inline-block;vertical-align: top;margin-top: 20px">
          <div style="display: inline-block;vertical-align: top;width: 80px;height: 80px;margin-right: 10px" @click="materialClick(img)">
            <el-image
                style="width: 80px; height: 80px;cursor: pointer"
                :src="img.url"
                :key="img.url"
                lazy
            />
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="materialDia = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "@/Axios/axios";

export default {
  data() {
    return {
      form: {},
      type: [],
      newForm: {},
      url: '',
      dialogVisible: false,
      srcList: [],
      randomKey: Math.random(),
      materialDia: false,
      material: [],
      token: {
        "token": window.sessionStorage.getItem("token"),
      },
      rules: {
        name: [
          {required: true, message: '请输入类型名称', trigger: 'blur'},
        ]
      },
    }
  },
  mounted() {
    this.select();
  },
  methods: {
    select() {
      console.log("本来是打算做分页的，但是考虑到复用以及用户体验，还是先不做了，留个坑，以后再来填");
      axios.post("/bill/billTypeList", this.form).then(res => {
        if (res.code === 200) {
          let data = res.data;
          data.forEach(item => {
            item.editFlag = false;
            item.status = item.status === 1;
            item.exclusive = item.exclusive === 1;
          });
          this.type = data;
          this.randomKey = Math.random();
        } else {
          this.$message.error(res.msg);
        }
      }).catch(() => {
      })
    },
    reset() {
      this.form = {};
      this.page = 1;
      this.select();
    },
    addNew() {
      this.dialogVisible = true;
    },
    handleClose(done) {
      this.dialogVisible = false;
      this.newForm = {};
      this.url = '';
      done();
    },
    materialClose(done) {
      this.materialDia = false;
      done();
    },
    handleAvatarSuccess(res) {
      if (res.code !== 200) {
        this.$message.error(res.msg);
      }
      this.$message.success("上传成功！");
      this.newForm.groupId = res.data.id;
      this.url = res.data.url;
      this.srcList.push(res.data.url);
    },

    beforeAvatarUpload(file) {
      const imageFormats = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
      const isImage = imageFormats.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('上传头像图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },

    submit() {
      if (this.newForm.name === undefined || this.newForm.name === "" || this.newForm.name === null) {
        this.$message.error("请输入类型名称");
        return;
      }
      if (this.newForm.groupId === undefined || this.newForm.groupId === "" || this.newForm.groupId === null) {
        this.$message.error("请上传类型图片");
        return;
      }
      axios.post("/bill/InsertNewType", this.newForm).then(res => {
        if (res.code === 200) {
          this.$message.success("新增成功");
          this.newForm = {};
          this.url = '';
          this.dialogVisible = false;
          this.select();
        } else {
          this.$message.error(res.msg);
        }
      }).catch(() => {
      })
    },
    errorHandler() {
      return true
    },
    editRow(row) {
      if (row.editFlag) {
        this.$confirm('是否确定修改类型：' + row.name + '?', '修改记账类型', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          row.status = row.status ? 1 : 0;
          row.exclusive = row.exclusive ? 1 : 0;
          axios.post("/bill/updateType", row).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '修改成功'
              });
              this.select();
            } else {
              this.$message({
                type: 'warning',
                message: res.msg
              });
            }
          }).catch(() => {
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消更改'
          });
        });
      }
      row.editFlag = !row.editFlag;
      this.randomKey = Math.random();
    },
    deleteRow(row) {
      if (row.editFlag) {
        row.editFlag = false;
        this.select();
        this.randomKey = Math.random();
        return;
      }
      this.$confirm('是否确定删除类型：' + row.name + '，' + '注：此操作不可逆！', '修改记账类型', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        axios.delete("/bill/deleteType/" + row.id).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            this.select();
          } else {
            this.$message({
              type: 'warning',
              message: res.msg
            });
          }
        }).catch(() => {
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消更改'
        });
      });
    },
    openMaterial() {
      let form = {};
      form.status = 1;
      form.type = 2;
      axios.post("materialLibrary/list", form).then(res => {
        if (res.code === 200) {
          this.material = res.data;
          this.materialDia = true;
        } else {
          this.$message.error("素材库为空，请自行上传吧！");
        }
      }).catch(() => {
      })
    },
    materialClick(item) {
      this.newForm.groupId = item.groupId;
      this.url = item.url;
      this.srcList.push(item.url);
      this.materialDia = false;
    }
  },
}
</script>

<style scoped>
.app {
  display: flex;
  flex-direction: column;
}

.el-input {
  width: 140px;
}

.el-select {
  width: 140px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border-radius: 50%;
}

.dialog >>> .el-dialog__header {
  height: 5px !important;
  line-height: 10px !important;
}

.dialog >>> .el-input {
  width: 90%;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
  margin-left: 25%;
}

.table {
  margin-left: 10px;
}

.table >>> .el-input {
  width: 80px !important;
}
</style>